<template>
  <div class="continer">
    <div id="cesiumContainer" class="cesiumContainer"></div>
    <!--
    <div style="position: absolute; z-index:100; left:0px; top:0px;"></div>
    -->
    <div style="position: absolute; z-index:100; left:0px; top:0px;">
      <button v-on:click="drawPoint()">
        点
      </button>
      <button v-on:click="drawPolyline()">
        线
      </button>
      <button v-on:click="drawCurve()">
        曲线
      </button>
      <button v-on:click="drawArc()">
        弓形线
      </button>
      <button v-on:click="drawCircle()">
        圆
      </button>
      <button v-on:click="drawFreeHandLine()">
        自由线
      </button>
      <button v-on:click="drawRectAngle()">
        矩形
      </button>
      <button v-on:click="drawEllipse()">
        椭圆
      </button>
      <button v-on:click="drawLune()">
        弓型面
      </button>
      <button v-on:click="drawSector()">
        扇形
      </button>
      <button v-on:click="drawClosedCurve()">
        闭合曲面
      </button>
      <button v-on:click="drawPolygon()">
        多边形
      </button>
      <button v-on:click="drawFreePolygon()">
        自由面
      </button>
      <button v-on:click="drawGatheringPlace()">
        集结地
      </button>
      <button v-on:click="drawDoubleArrow()">
        双箭头
      </button>
      <button v-on:click="drawStraightArrow()">
        细直箭头
      </button>
      <button v-on:click="drawFineArrow()">
        粗单尖头箭头
      </button>
      <button v-on:click="drawAttackArrow()">
        进攻方向
      </button>
      <button v-on:click="drawAssaultDirection()">
        粗单直箭头
      </button>
      <button v-on:click="drawTailedAttackArrow()">
        进攻方向(尾)
      </button>
      <button v-on:click="drawSquadCombat()">
        分队战斗行动
      </button>
      <button v-on:click="drawTailedSquadCombat()">
        分队战斗行动(尾)
      </button>
      <button v-on:click="drawRectFlag()">
        矩形标志旗
      </button>
      <button v-on:click="drawTriangleFlag()">
        三角标志旗
      </button>
      <button v-on:click="drawCurveFlag()">
        曲线标志旗
      </button>
      <button v-on:click="drawA318()">
        A318
      </button>
      <button v-on:click="drawA319()">
        A319
      </button>
      <button v-on:click="drawA380()">
        A380
      </button>
    </div>
  </div>
</template>

<script>
// eslint-disable-next-line no-unused-vars
import * as Cesium from "cesium/Build/Cesium/Cesium";
// import axios from "axios";
import "cesium/Build/Cesium/Widgets/widgets.css";

import CesiumPlot from "./plot/index";
import * as Utils from "./plot/utils/Utils";

let viewer = null;
let plot = null;
export default {
  name: "Cesium",
  data() {
    return {
      handle: null,
      plot: null,
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.init();
    });
  },
  methods: {
    init() {
      let that = this;
      Cesium.Ion.defaultAccessToken =
        "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJmNTZmY2U0Ni1lMmMxLTQ1ZmMtYWIyZC1hZDk2NzE5N2UzMDciLCJpZCI6MjU5LCJpYXQiOjE2MDQzMjY0MjN9.aTMKOaHQKGyesz1A2QXE-Y5FvG19FSO7I6F3NS1T5To";
      let viewerOption = {
        //需要进行可视化的数据源的集合
        animation: false, //是否显示动画控件
        shouldAnimate: true,
        homeButton: false, //是否显示Home按钮
        fullscreenButton: false, //是否显示全屏按钮
        baseLayerPicker: false, //是否显示图层选择控件
        geocoder: false, //是否显示地名查找控件
        timeline: false, //是否显示时间线控件
        sceneModePicker: false, //是否显示投影方式控件
        navigationHelpButton: false, //是否显示帮助信息控件
        infoBox: false, //是否显示点击要素之后显示的信息
        requestRenderMode: true, //启用请求渲染模式
        scene3DOnly: false, //每个几何实例将只能以3D渲染以节省GPU内存
        sceneMode: 3, //初始场景模式 1 2D模式 2 2D循环模式 3 3D模式  Cesium.SceneMode
        skyBox: false,
        //fullscreenElement: document.body, //全屏时渲染的HTML元素 暂时没发现用处
        // eslint-disable-next-line no-undef
        terrainProvider: Cesium.createWorldTerrain({
          requestWaterMask: true,
        }),
        // eslint-disable-next-line no-undef
        //terrainProvider: new Cesium.CesiumTerrainProvider({
        //  url: "http://localhost:8080/terrain/",
        //"http://193.169.100.214:9000/terrain/982b8150c67611eab296dd21ee1a8d5b",
        //  requestWaterMask: true
        //})
      };
      viewer = new Cesium.Viewer("cesiumContainer", viewerOption);
      viewer._cesiumWidget._creditContainer.style.display = "none"; // 隐藏版权

      viewer.camera.setView({
        destination: Cesium.Cartesian3.fromDegrees(
          80.963745,
          35.634977,
          300000
        ),
        orientation: {
          heading: Cesium.Math.toRadians(0), // east, default value is 0.0 (north)
          pitch: Cesium.Math.toRadians(-90), // default value (looking down)
          roll: 0.0, // default value
        },
      });

      plot = new CesiumPlot(viewer, {
        zoomToExtent: false,
      });

      if (!that.handler) {
        that.handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
      }
      // 左键单击事件：
      that.handler.setInputAction(function(e) {
        var pick = viewer.scene.pick(e.position);
        if (Cesium.defined(pick)) {
          if (pick.id && pick.id.plot) {
            plot.plotEdit.activate(pick.id);
          } else {
            plot.plotEdit.deactivate();
          }
        }
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    },
    drawPoint() {
      plot.plotDraw.active("Point");
    },
    drawPolyline() {
      plot.plotDraw.active("Polyline");
    },
    drawCurve() {
      plot.plotDraw.active("Curve");
    },
    drawArc() {
      plot.plotDraw.active("Arc");
    },
    drawCircle() {
      plot.plotDraw.active("Circle");
    },
    drawFreeHandLine() {
      plot.plotDraw.active("FreeHandLine");
    },
    drawRectAngle() {
      plot.plotDraw.active("RectAngle");
    },
    drawEllipse() {
      plot.plotDraw.active("Ellipse");
    },
    drawLune() {
      plot.plotDraw.active("Lune");
    },
    drawSector() {
      plot.plotDraw.active("Sector");
    },
    drawClosedCurve() {
      plot.plotDraw.active("ClosedCurve");
    },
    drawPolygon() {
      plot.plotDraw.active("Polygon");
    },
    drawFreePolygon() {
      plot.plotDraw.active("FreePolygon");
    },
    drawGatheringPlace() {
      plot.plotDraw.active("GatheringPlace");
    },
    drawDoubleArrow() {
      plot.plotDraw.active("DoubleArrow");
    },
    drawStraightArrow() {
      plot.plotDraw.active("StraightArrow");
    },
    drawFineArrow() {
      plot.plotDraw.active("FineArrow");
    },
    drawAttackArrow() {
      plot.plotDraw.active("AttackArrow");
    },
    drawAssaultDirection() {
      plot.plotDraw.active("AssaultDirection");
    },
    drawTailedAttackArrow() {
      plot.plotDraw.active("TailedAttackArrow");
    },
    drawSquadCombat() {
      plot.plotDraw.active("SquadCombat");
    },
    drawTailedSquadCombat() {
      plot.plotDraw.active("TailedSquadCombat");
    },
    drawRectFlag() {
      plot.plotDraw.active("RectFlag");
    },
    drawTriangleFlag() {
      plot.plotDraw.active("TriangleFlag");
    },
    drawCurveFlag() {
      plot.plotDraw.active("CurveFlag");
    },
    drawA380() {
      let curvePath = Utils.getCurvePoints(0.3, [
        [80.875854, 35.496456],
        [80.425415, 35.406961],
        [80.304565, 35.670685],
        [80.776978, 35.929093],
      ]);
      for (let i = 0; i < curvePath.length; i++) {
        curvePath[i] = curvePath[i].concat([8000]);
        // if (i > 10 && i < curvePath.length - 10) {
        //   height = height + 10;
        // }
      }

      const timeStepInSeconds = 33;
      const totalSeconds = timeStepInSeconds * (curvePath.length - 1);
      const start = Cesium.JulianDate.fromIso8601("2020-03-09T23:10:00Z");
      const stop = Cesium.JulianDate.addSeconds(
        start,
        totalSeconds,
        new Cesium.JulianDate()
      );

      const positionProperty = new Cesium.SampledPositionProperty();
      for (let i = 0; i < curvePath.length; i++) {
        const dataPoint = curvePath[i];
        const time = Cesium.JulianDate.addSeconds(
          start,
          i * timeStepInSeconds,
          new Cesium.JulianDate()
        );
        const position = Cesium.Cartesian3.fromDegrees(
          dataPoint[0],
          dataPoint[1],
          dataPoint[2]
        );
        positionProperty.addSample(time, position);
      }

      const airplaneEntity = viewer.entities.add({
        availability: new Cesium.TimeIntervalCollection([
          new Cesium.TimeInterval({ start: start, stop: stop }),
        ]),
        position: positionProperty,
        // Attach the 3D model instead of the green point.
        model: {
          uri: "models/a380.glb",
          maximumScale: 1,
          minimumPixelSize: 1024,
        },
        // Automatically compute the orientation from the position.
        //orientation: new Cesium.VelocityOrientationProperty(positionProperty),
        orientation: new Cesium.CallbackProperty(function(time, value) {
          console.log(value);
          let quaternion = new Cesium.VelocityOrientationProperty(
            positionProperty
          ).getValue(time);
          // console.log(Cesium.Matrix3.fromQuaternion(value));

          let B = airplaneEntity.position.getValue(time);
          let chicB = Cesium.Cartographic.fromCartesian(B);
          chicB.height = 0;
          let dB = Cesium.Cartographic.toCartesian(chicB);
          let normaB = Cesium.Cartesian3.normalize(
            Cesium.Cartesian3.subtract(dB, B, new Cesium.Cartesian3()),
            new Cesium.Cartesian3()
          );
          console.log(normaB);

          var Q = Cesium.Quaternion.fromAxisAngle(
            normaB,
            Cesium.Math.toRadians(90)
          );
          var m3 = Cesium.Matrix3.fromQuaternion(Q);
          var m4 = Cesium.Matrix4.fromRotationTranslation(m3);
          // http://henggetec.com/?mod=news_detail&id=31
          return quaternion;
        }),
        path: new Cesium.PathGraphics({ width: 3 }),
      });

      viewer.clock.startTime = start.clone();
      viewer.clock.stopTime = stop.clone();
      viewer.clock.currentTime = start.clone();
      //viewer.timeline.zoomTo(start, stop);
      // Speed up the playback speed 50x.
      viewer.clock.multiplier = 10;
      // Start playing the scene.
      viewer.clock.shouldAnimate = true;
      viewer.trackedEntity = airplaneEntity;
    },
    drawA318() {
      let curvePath = Utils.getCurvePoints(0.3, [
        [80.875854, 35.496456],
        [80.445415, 35.426961],
        [80.364565, 35.620685],
        [80.786978, 35.829093],
      ]);
      for (let i = 0; i < curvePath.length; i++) {
        curvePath[i] = curvePath[i].concat([7950]);
        // if (i > 10 && i < curvePath.length - 10) {
        //   height = height + 10;
        // }
      }

      const timeStepInSeconds = 30;
      const totalSeconds = timeStepInSeconds * (curvePath.length - 1);
      const start = Cesium.JulianDate.fromIso8601("2020-03-09T23:10:00Z");
      const stop = Cesium.JulianDate.addSeconds(
        start,
        totalSeconds,
        new Cesium.JulianDate()
      );

      const positionProperty = new Cesium.SampledPositionProperty();
      for (let i = 0; i < curvePath.length; i++) {
        const dataPoint = curvePath[i];
        const time = Cesium.JulianDate.addSeconds(
          start,
          i * timeStepInSeconds,
          new Cesium.JulianDate()
        );
        const position = Cesium.Cartesian3.fromDegrees(
          dataPoint[0],
          dataPoint[1],
          dataPoint[2]
        );
        positionProperty.addSample(time, position);
      }

      const airplaneEntity = viewer.entities.add({
        availability: new Cesium.TimeIntervalCollection([
          new Cesium.TimeInterval({ start: start, stop: stop }),
        ]),
        position: positionProperty,
        // Attach the 3D model instead of the green point.
        model: { uri: "models/a318.glb" },
        // Automatically compute the orientation from the position.
        orientation: new Cesium.VelocityOrientationProperty(positionProperty),
        // orientation: new Cesium.CallbackProperty(function() {
        //   //console.log(this.getValue(viewer.clock.currentTime));
        //   return new Cesium.VelocityOrientationProperty(positionProperty);
        // }),
        path: new Cesium.PathGraphics({ width: 3 }),
      });

      viewer.clock.startTime = start.clone();
      viewer.clock.stopTime = stop.clone();
      viewer.clock.currentTime = start.clone();
      //viewer.timeline.zoomTo(start, stop);
      // Speed up the playback speed 50x.
      viewer.clock.multiplier = 10;
      // Start playing the scene.
      viewer.clock.shouldAnimate = true;
      viewer.trackedEntity = airplaneEntity;
    },
    drawA319() {
      let curvePath = Utils.getCurvePoints(0.3, [
        [80.875854, 35.496456],
        [80.325415, 35.506961],
        [80.204565, 35.770685],
        [80.776978, 35.929093],
      ]);
      for (let i = 0; i < curvePath.length; i++) {
        curvePath[i] = curvePath[i].concat([7900]);
        // if (i > 10 && i < curvePath.length - 10) {
        //   height = height + 10;
        // }
      }

      const timeStepInSeconds = 32;
      const totalSeconds = timeStepInSeconds * (curvePath.length - 1);
      const start = Cesium.JulianDate.fromIso8601("2020-03-09T23:10:00Z");
      const stop = Cesium.JulianDate.addSeconds(
        start,
        totalSeconds,
        new Cesium.JulianDate()
      );

      const positionProperty = new Cesium.SampledPositionProperty();
      for (let i = 0; i < curvePath.length; i++) {
        const dataPoint = curvePath[i];
        const time = Cesium.JulianDate.addSeconds(
          start,
          i * timeStepInSeconds,
          new Cesium.JulianDate()
        );
        const position = Cesium.Cartesian3.fromDegrees(
          dataPoint[0],
          dataPoint[1],
          dataPoint[2]
        );
        positionProperty.addSample(time, position);
      }

      const airplaneEntity = viewer.entities.add({
        availability: new Cesium.TimeIntervalCollection([
          new Cesium.TimeInterval({ start: start, stop: stop }),
        ]),
        position: positionProperty,
        // Attach the 3D model instead of the green point.
        model: { uri: "models/a319.glb" },
        // Automatically compute the orientation from the position.
        orientation: new Cesium.VelocityOrientationProperty(positionProperty),
        // orientation: new Cesium.CallbackProperty(function() {
        //   //console.log(this.getValue(viewer.clock.currentTime));
        //   return new Cesium.VelocityOrientationProperty(positionProperty);
        // }),
        path: new Cesium.PathGraphics({ width: 3 }),
      });

      viewer.clock.startTime = start.clone();
      viewer.clock.stopTime = stop.clone();
      viewer.clock.currentTime = start.clone();
      //viewer.timeline.zoomTo(start, stop);
      // Speed up the playback speed 50x.
      viewer.clock.multiplier = 10;
      // Start playing the scene.
      viewer.clock.shouldAnimate = true;
      viewer.trackedEntity = airplaneEntity;
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
.continer .cesiumContainer {
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0px;
  top: 0px;
  margin: 0;
  padding: 0;
  bottom: 0;
}
</style>
